<template>
  <div class="container">
    <div class="choose-item">
      <ul v-if="versionType === 'jiaokong'">
        <!-- '文档纠错', '专业翻译', '日志辅助分析', -->
        <li
          v-for="item in ['文档纠错', '专业翻译', '公文写作', '测试点生成']"
          @click="handleClickIntelligent(item)"
          :key="item"
          :class="{ active: currentIntelligent === item }"
        >
          {{ item }}
        </li>
      </ul>
      <ul v-if="versionType === 'nanning'">
        <li
          v-for="item in ['公文写作']"
          @click="handleClickIntelligent(item)"
          :key="item"
          :class="{ active: currentIntelligent === item }"
        >
          {{ item }}
        </li>
      </ul>
    </div>

    <div class="mainStyle" style="display: block" v-loading="waitLoading">
      <div
        class="select-container"
        v-if="currentIntelligent !== '文档纠错' && currentIntelligent !== '测试点生成'"
      >
        <div v-if="currentIntelligent === '文档纠错'">
          <span class="tag-text">
            推荐问题：
            <br />
            车载ATP系统是车载系统的贺信控制设备，车载ATP系统为行车安全和列车驾驶（司机或设备自动驾驶）提供辅助和监督，防止由于列车敌对运行所引起的冲撞；防止由于非正常的车门打开、列车退行等事故而使旅客发生危险；放置由于列车超过限制速度或者命令速度为导致列车发生危险或对线路造成损坏。ATP系统采用3取2冗余技术，降低了系统的可靠性、安全性和可用性。
            ATP软件运行在ATP子子系统中的三块ATP主机板中中，且三块主机板中的ATP软件完全相同；ATP三块主机板上电后经过硬件自检、软件初始化、ATP3取2平台表决，如果都失败后，进入周期运行阶段，进行ATP应用处理和平台控制，ATP软件运行所需的输入信息是从平台获取，输出信息经过平台表决通过后经通信板发送给ATO或通信控制器发送给。
          </span>
        </div>
        <div v-if="currentIntelligent === '专业翻译'">
          <span class="tag-text" style="padding-bottom: 4px">
            提示：1. 所上传文档文档第二列为中文、第三列为对应的英文翻译
            <br />
          </span>
          <uploadItem @call-parent="parentMethod"></uploadItem>

          <el-radio-group v-model="fileName" size="small">
            <template v-for="(item, index) in translateList">
              <el-radio :label="item" border>{{ item }}</el-radio>
              <el-button
                style="margin-left: 10px; margin-right: 20px"
                type="text"
                size="small"
                @click="deleteFile(item)"
                >删除</el-button
              >
            </template>
          </el-radio-group>
        </div>
        <div v-if="currentIntelligent === '日志辅助分析'">
          <uploadItem2
            @call-parent="parentMethod"
            title="文件"
            :limit="[
              {
                lable: 'xlsx',
                value: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
              },
            ]"
            url="/agent/loganalyst/upload_log_file"
          ></uploadItem2>

          <el-radio-group v-model="guzhangFile" size="small">
            <template v-for="item in logList">
              <el-radio :label="item" border>{{ item }}</el-radio>
              <el-button
                style="margin-left: 10px; margin-right: 20px"
                type="text"
                size="small"
                @click="deleteLog(item)"
                >删除</el-button
              >
            </template>
          </el-radio-group>

          <el-tag size="small" style="margin-right: 10px">
            推荐问题1：查询传感器1辅助速不一致的时间和序列号信息
          </el-tag>
          <el-tag size="small"> 推荐问题2：查询传感器1状态故障的时间和序列号信息 </el-tag>
        </div>
        <div v-if="currentIntelligent === '公文写作'">
          <div class="meet-item">
            <uploadItem2
              @call-parent="parentMethod"
              title="会议记录"
              :limit="[
                {
                  lable: 'txt',
                  value: 'text/plain',
                },
              ]"
              url="/agent/writer/upload_meeting_transcript"
            ></uploadItem2>

            <el-radio-group v-model="huiyi.meeting_transcript_file_name" size="small">
              <template v-for="item in itemList1">
                <el-radio :label="item" border>{{ item }}</el-radio>
                <el-button
                  style="margin-left: 10px; margin-right: 20px"
                  type="text"
                  size="small"
                  @click="
                    deleteNotice(
                      item,
                      '/agent/writer/drop_transcript',
                      'transcript_file_name',
                      '公文写作',
                    )
                  "
                  >删除</el-button
                >
              </template>
            </el-radio-group>
          </div>

          <div class="meet-item">
            <uploadItem2
              @call-parent="parentMethod"
              title="会前通知"
              :limit="[
                {
                  lable: 'docx',
                  value: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                },
                { lable: '、doc', value: 'application/msword' },
              ]"
              url="/agent/writer/upload_meeting_notice"
            ></uploadItem2>
            <el-radio-group v-model="huiyi.meeting_notice_file_name" size="small">
              <template v-for="item in itemList2">
                <el-radio :label="item" border>{{ item }}</el-radio>
                <el-button
                  style="margin-left: 10px; margin-right: 20px"
                  type="text"
                  size="small"
                  @click="
                    deleteTranscript(
                      item,
                      '/agent/writer/drop_meeting_notice',
                      'meeting_notice_file_name',
                      '公文写作',
                    )
                  "
                  >删除</el-button
                >
              </template>
            </el-radio-group>
          </div>
          <div class="meet-item meet-item-2">
            <uploadItem5
              @call-parent="parentMethod"
              title="会议附件"
              :limit="[
                {
                  lable: 'docx',
                  value: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                },
                { lable: '、doc', value: 'application/msword' },
              ]"
              url="/agent/writer/upload_meeting_attachment"
            ></uploadItem5>

            <el-checkbox-group v-model="huiyi.meeting_attachment_file_name" size="small">
              <template v-for="item in itemList3">
                <el-checkbox :label="item" border>{{ item }}</el-checkbox>
                <el-button
                  style="margin-left: 10px; margin-right: 20px"
                  type="text"
                  size="small"
                  @click="
                    deleteTranscript(
                      item,
                      '/agent/writer/drop_meeting_attachment',
                      'meeting_attachment_file_name',
                      '公文写作',
                    )
                  "
                  >删除</el-button
                >
              </template>
            </el-checkbox-group>
            <el-button
              size="small"
              type="danger"
              style="margin-top: 10px"
              v-if="itemList3.length >= 3"
              @click="deleteAll"
            >
              一键删除
            </el-button>
          </div>
        </div>
      </div>
      <div class="select-container select-container2" v-if="currentIntelligent === '测试点生成'">
        <point @saveMessage="saveMessage"></point>
      </div>
      <div class="select-container" v-if="currentIntelligent === '文档纠错'">
        <doc></doc>
        <correct-file
          v-if="showTransFile && currentIntelligent === '文档纠错'"
          @call-parent="submitQa"
          @change-parent="handleClickShow"
        ></correct-file>
        <div class="chatInput pos-container">
          <el-input
            @keyup.enter.native="handleSubmit"
            v-if="currentIntelligent === '文档纠错' && !showTransFile"
            @input="getValue"
            v-model="chatInput"
            :placeholder="selectType == 1 ? '请输入提问内容' : '请输入搜索关键字'"
            class="input-with-select input-with-select2"
          >
          </el-input>
          <el-button
            v-if="currentIntelligent === '文档纠错' && !showTransFile"
            type="primary"
            size="small"
            class="inear-chat-btn"
            style="top: 10px; right: 10px"
            @click.native="handleSubmit"
            >{{ selectType == 1 ? '发送' : '搜索' }}</el-button
          >
          <el-button
            v-if="currentIntelligent === '文档纠错' && !showTransFile"
            size="small"
            @click="handleClickShow"
            style="top: 10px; right: 74px"
            class="inear-chat-btn"
            >选择文件纠错</el-button
          >
        </div>
      </div>
      <!-- 文档纠错 -->
      <div class="contentRight columnFlex">
        <!-- {{ messages }} -->
        <div
          class="chatBox"
          ref="chatBox"
          :class="currentIntelligent === '测试点生成' ? 'chatBox2' : ''"
        >
          <div class="leftBox">
            <img src="@/assets/image/robot.png" class="userIcon" />
            <div class="msgtext">您好！</div>
          </div>
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="index % 2 == 0 ? 'rightBox' : 'leftBox'"
          >
            <img v-if="index % 2 != 0" src="@/assets/image/robot.png" class="userIcon" />

            <div class="msgtext">
              <p v-html="message.text"></p>
            </div>
            <img v-if="index % 2 == 0" src="@/assets/image/user.png" class="userIcon" />
          </div>
        </div>
        <div class="chatInput">
          <!-- 文件纠错模块 -->

          <!-- 文件翻译模块 -->
          <trans-file
            v-if="showTransFile && currentIntelligent === '专业翻译'"
            :fileName="fileName"
            @call-parent="submitQa"
            @change-parent="handleClickShow"
          ></trans-file>
          <el-input
            @keyup.enter.native="handleSubmit"
            v-if="currentIntelligent === '专业翻译' || currentIntelligent === '日志辅助分析'"
            @input="getValue"
            v-model="chatInput"
            :placeholder="selectType == 1 ? '请输入提问内容' : '请输入搜索关键字'"
            class="input-with-select"
          >
          </el-input>
          <el-button
            v-if="currentIntelligent === '专业翻译' || currentIntelligent === '日志辅助分析'"
            type="primary"
            size="small"
            class="sendBtn"
            @click.native="handleSubmit"
            >{{ selectType == 1 ? '发送' : '搜索' }}</el-button
          >
          <el-button
            v-if="currentIntelligent === '公文写作' || currentIntelligent === '智能会议记录'"
            type="primary"
            size="small"
            style="width: 100%"
            @click.native="handleSubmit"
            >{{ selectType == 1 ? '发送' : '搜索' }}</el-button
          >
          <el-button
            v-if="currentIntelligent === '专业翻译'"
            size="small"
            @click="handleClickShow"
            class="inear-chat-btn"
            >选择文件翻译</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getData, postData } from '@/service/getData';
import axios from 'axios';

import { fetchEventSource } from '@microsoft/fetch-event-source';

import pdfPreview from '@/components/common/pdfPreview.vue';

import uploadItem from '../../components/upload-item.vue';
import uploadItem2 from '../../components/upload-item-2.vue';
import uploadItem5 from '../../components/upload-item-5.vue';
import uploadItem4 from '../../components/upload-item-2.vue';
import transFile from '../../components/trans_file.vue';
import correctFile from '../../components/correct_file.vue';
import point from '../../components/point.vue';
import doc from '../../components/doc.vue';
export default {
  components: {
    pdfPreview,
    uploadItem,
    uploadItem2,
    uploadItem5,
    uploadItem4,
    transFile,
    correctFile,
    point,
    doc,
  },
  // 注册组件
  data() {
    return {
      chat_id: null, // 多轮问答
      versionType: process.env.VUE_APP_BASE_API,
      isRequesting: false, // 是否正在请求
      abortController: null, // 用于取消请求的 AbortController
      uploadParams: {
        uploadUrl: '/agent/corrector/upload_original_file',
        data: {},
        headers: {
          Authorization: '',
        },
        name: 'file',
        fileLists: [],
      },
      // 是否显示文件翻译
      showTransFile: false,
      fileName: '迪士尼专业术语翻译.xlsx',
      // 文档纠错
      currentIntelligent: '测试点生成',
      guzhangList: [
        {
          text: '查询传感器1辅助速不一致的时间和序列号信息',
          filename: '故障1.xlsx',
        },
        {
          text: '查询传感器1状态故障的时间和序列号信息',
          filename: '故障2.xlsx',
        },
      ],
      guzhangFile: '故障1.xlsx',
      role: 'user', // admin
      waitLoading: false,
      keyValue: '',
      imageUrl: '',
      pdfUrl: '',
      compiledMarkdown: '',

      markdownContent: '',
      messages: [],
      save_topk_paragraphs: [],
      topk_paragraphs: [],
      treeDataTemp: [],
      text: '',
      chatInput: '',
      treeData: [],
      levelOneSel: '',
      files: [],
      commitShow: false,
      currentId: '',
      commitForm: {
        score: 0,
        comment: '',
      },
      link: '',
      showSearch: false,
      SeachList: [],
      SeachListSelect: [],
      selectType: '1',
      searchFileList: [],
      seachFlag: false,
      typeValue: '',
      watermark: '交控科技',
      partition_names: [],
      levelTwoSelList: [],
      translateList: [],
      logList: [],
      officialList: [],
      officialFile: '',
      meetingNotice: [],
      meetingTranscript: [],
      meetingNoticeList: [],
      meetingTranscriptList: [],
      itemList1: [],
      itemList2: [],
      itemList3: [],
      huiyi: {
        meeting_transcript_file_name: '',
        meeting_notice_file_name: '',
        meeting_attachment_file_name: [],
      },
      notice: {
        meeting_notice_file_name: '',
        meeting_minutes_file_name: '',
      },
      meeting: {
        meeting_notice_file_name: '',
        meeting_transcript_file_name: '',
      },
    };
  },
  mounted() {
    let token = localStorage.getItem('token');
    this.uploadParams.headers['Authorization'] = 'Token ' + token;
    if (this.versionType === 'nanning') {
      this.currentIntelligent = '公文写作';
    }
    this.parentMethod();
  },
  beforeDestroy() {},

  methods: {
    saveMessage(obj) {
      if (obj.type === 'add') {
        this.messages.push({
          text: obj.input_text,
        });
      } else if (obj.type === 'clear') {
        this.messages = [];
      } else {
        this.messages[this.messages.length - 1].text = obj.input_text;
      }
    },
    submitQa(text, type) {
      // type 类型为true 的情况是 替换文字内容
      if (type) {
        this.messages[this.messages.length - 1].text = text;
      } else {
        this.messages.push({
          text: text,
        });
      }
    },
    handleClickShow() {
      this.showTransFile = !this.showTransFile;
    },
    // 删除文件
    deleteFile(item) {
      axios
        .post(
          '/agent/translate/drop_glossary',
          {
            glossary_file_name: item,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message.success('文件删除成功');
          this.parentMethod();
        });
    },
    deleteLog(item) {
      axios
        .post(
          '/agent/loganalyst/drop_log',
          {
            log_file_name: item,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message.success('文件删除成功');
          this.parentMethod();
        });
    },
    deleteOfficial(item) {
      axios
        .post(
          '/agent/writer/drop_official_document',
          {
            official_document_file_name: item,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message.success('文件删除成功');
          this.parentMethod();
        });
    },
    // 删除会前通知
    deleteNotice(item, str, keyName, type) {
      // 判断一下当前是否选中
      axios
        .post(
          str,
          {
            [keyName]: item,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message.success('文件删除成功');
          if (type === '智能会议记录') {
            if (this.notice.meeting_notice_file_name === item) {
              this.notice.meeting_notice_file_name = '';
            }
          } else if (type === '公文写作') {
            if (this.meeting.meeting_notice_file_name === item) {
              this.meeting.meeting_notice_file_name = '';
            }
          }
          this.parentMethod();
        });
    },
    // 删除会议记录
    deleteAll() {
      var _this = this;
      this.itemList3.forEach((item) => {
        _this.deleteTranscript(
          item,
          '/agent/writer/drop_meeting_attachment',
          'meeting_attachment_file_name',
          '公文写作',
        );
      });
    },

    deleteTranscript(item, str, keyName, type) {
      axios
        .post(
          str,
          {
            [keyName]: item,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.$message.success('文件删除成功');
          if (type === '智能会议记录') {
            if (this.notice.meeting_minutes_file_name === item) {
              this.notice.meeting_minutes_file_name = '';
            }
          } else if (type === '公文写作') {
            if (this.meeting.meeting_transcript_file_name === item) {
              this.meeting.meeting_transcript_file_name = '';
            }
          }
          this.parentMethod();
        });
    },
    // 获取翻译智能体的文件列表
    getTranslateFileList() {
      axios
        .post(
          '/agent/translate/list_glossaries',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.translateList = res.data.files;
          }
        });
    },
    getLogFileList() {
      axios
        .post(
          '/agent/loganalyst/list_logs',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.logList = res.data.files;
          }
        });
    },
    getOfficialFileList() {
      axios
        .post(
          '/agent/writer/list_official_documents',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.officialList = res.data.files;
            // 默认选择第一项
            if (this.officialList.length > 0) {
              this.officialFile = this.officialList[0];
            }
          }
        });
    },
    // 获取会前通知
    getNoticeFileList() {
      axios
        .post(
          '/agent/writer/list_notice',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.meetingNotice = res.data.files;
            // 默认选择第一项
            if (this.meetingNotice.length > 0) {
              this.meeting.meeting_notice_file_name = this.meetingNotice[0];
            }
          }
        });
    },
    // 123
    getWriterNoticeFileList() {
      axios
        .post(
          '/agent/writer/list_transcript',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.itemList1 = res.data.files;
            // 默认选择第一项
            if (this.itemList1.length > 0) {
              this.huiyi.meeting_transcript_file_name = this.itemList1[0];
            }
          }
        });
    },
    getMeetingAttachmentList() {
      axios
        .post(
          '/agent/writer/list_meeting_attachment',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.itemList3 = res.data.files;
            // 默认选择第一项
            if (this.itemList3.length > 0) {
              this.huiyi.meeting_attachment_file_name = this.itemList3;
            }
          }
        });
    },
    // 获取会议记录
    getTranscriptFileList() {
      axios
        .post(
          '/agent/writer/list_transcript',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.itemList1 = res.data.files;
            // 默认选择第一项
            if (this.itemList1.length > 0) {
              this.huiyi.meeting_transcript_file_name = this.itemList1[0];
            }
          }
        });
    },
    getWriterTranscriptFileList() {
      axios
        .post(
          '/agent/writer/list_notice',
          {},
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          if (res && res.status == 200) {
            this.itemList2 = res.data.files;
            // 默认选择第一项
            if (this.itemList2.length > 0) {
              this.huiyi.meeting_notice_file_name = this.itemList2[0];
            }
          }
        });
    },
    clearMesaage() {
      this.messages = [];
    },
    handleClickIntelligent(item) {
      // 清空输入框内容
      this.chatInput = '';
      // 改为默认类型
      this.showTransFile = false;
      this.currentIntelligent = item;
      switch (item) {
        case '文档纠错':
          break;
        case '专业翻译':
          this.getTranslateFileList();
          break;
        case '日志辅助分析':
          this.getLogFileList();
          break;
        case '公文写作':
          this.getWriterNoticeFileList();
          this.getWriterTranscriptFileList();
          this.getMeetingAttachmentList();
          break;
      }
      this.clearMesaage();
    },
    parentMethod() {
      switch (this.currentIntelligent) {
        case '文档纠错':
          break;
        case '专业翻译':
          this.getTranslateFileList();
          break;
        case '日志辅助分析':
          this.getLogFileList();
          break;
        case '公文写作':
          this.getWriterNoticeFileList();
          this.getWriterTranscriptFileList();
          this.getMeetingAttachmentList();
          break;
      }
    },

    handleClickSearch(item) {
      console.log('index', index);
      item.showSearch = true;
    },
    //查询关联文件
    getValue() {
      this.seachFlag = false;
    },
    //查询关联文件

    //提问
    handleSubmit() {
      this.handleChatSubmit();
    },
    // post请求
    handleChatSubmit() {
      let _this = this;
      // this.chatInput
      if (this.currentIntelligent === '智能会议记录') {
        this.messages.push({
          text: '智能会议记录',
        });
      } else if (this.currentIntelligent === '公文写作') {
        this.messages.push({
          text: '公文写作',
        });
      } else {
        if (!this.chatInput) {
          return;
        }
        this.messages.push({
          text: this.chatInput,
        });
      }

      let chatInput = this.chatInput;
      this.chatInput = '';

      this.$nextTick(() => {
        let chatBox = this.$refs.chatBox;
        console.log(chatBox.scrollHeight);
        chatBox.scrollTop = chatBox.scrollHeight;
      });
      console.log(this.treeDataTemp);

      this.messages.push({
        text: '思考中，请稍候...',
      });
      this.save_topk_paragraphs.push([]);

      this.$nextTick(() => {
        let chatBox = this.$refs.chatBox;
        chatBox.scrollTop = chatBox.scrollHeight;
      });

      // 判断智能体类型
      switch (this.currentIntelligent) {
        case '文档纠错':
          axios
            .post(
              '/agent/corrector/correct_text',
              {
                input_text: chatInput,
              },
              {
                headers: {
                  Authorization: this.uploadParams.headers['Authorization'],
                },
              },
            )
            .then((res) => {
              if (res.data.code === 200) {
                this.handleChatSubmit2(
                  res.data.task_id,
                  '/agent/corrector/correct_text_sse',
                  'corrected_text',
                  false,
                );
              } else {
                _this.messages[_this.messages.length - 1].text = '服务开小差了，请稍后重试';
              }
            });
          break;
        case '专业翻译':
          axios
            .post(
              '/agent/translate/translate',
              {
                input_text: chatInput,
                glossary_file_name: this.fileName,
              },
              {
                headers: {
                  Authorization: this.uploadParams.headers['Authorization'],
                },
              },
            )
            .then((res) => {
              if (res.data.status === 200) {
                _this.messages[_this.messages.length - 1].text = res.data.translated_text;
              } else {
                _this.messages[_this.messages.length - 1].text = '服务开小差了，请稍后重试';
              }
            });
          break;
        case '日志辅助分析':
          axios
            .post(
              '/agent/loganalyst/analyse',
              {
                user_question: chatInput,
                log_file_name: this.guzhangFile,
              },
              {
                headers: {
                  Authorization: this.uploadParams.headers['Authorization'],
                },
              },
            )
            .then((res) => {
              console.log(res, res.data, res.data.task_id, '!!!!!!!!!!!!!!!');
              this.handleChatSubmit2(
                res.data.task_id,
                'agent/loganalyst/analyse_sse',
                'analysed_text',
                false,
                '',
              );
            });
          break;
        case '智能会议记录':
          if (
            this.huiyi.transcript_file_name === '' ||
            this.huiyi.meeting_notice_file_name === ''
          ) {
            this.messages[_this.messages.length - 1].text =
              '请选择会议纪要和会议通知,文件不能为空 ';
            return;
          }
          axios
            .post(
              '/agent/writer/write',
              {
                meeting_transcript_file_name: this.huiyi.transcript_file_name,
                meeting_notice_file_name: this.huiyi.meeting_notice_file_name,
              },
              {
                headers: {
                  Authorization: this.uploadParams.headers['Authorization'],
                },
              },
            )
            .then((res) => {
              // 转为流式

              this.handleChatSubmit2(
                res.data.task_id,
                '/agent/writer/write_sse',
                'write_text',
                true,
                '/agent/writer/download_official_document',
              );
            });
          break;
        case '公文写作':
          if (
            this.huiyi.meeting_notice_file_name === '' ||
            this.huiyi.meeting_transcript_file_name === ''
          ) {
            this.messages[_this.messages.length - 1].text =
              '请选择会议通知和会议记录,文件不能为空 ';
            return;
          }
          axios
            .post(
              '/agent/writer/write',
              {
                meeting_notice_file_name: this.huiyi.meeting_notice_file_name,
                meeting_transcript_file_name: this.huiyi.meeting_transcript_file_name,
              },
              {
                headers: {
                  Authorization: this.uploadParams.headers['Authorization'],
                },
              },
            )
            .then((res) => {
              this.handleChatSubmit2(
                res.data.task_id,
                'agent/writer/write_sse',
                'summarized_text',
                true,
                '/agent/writer/download_official_document',
              );
            });
          break;
      }
    },
    // 流式请求 taskid 任务id str 流式接口地址 type 类型 isMeeting 是否是会议记录 downloadUrl 下载地址
    handleChatSubmit2(id, str, type, isMeeting, downloadUrl) {
      let _this = this;
      if (_this.isRequesting) return;
      _this.isRequesting = true;

      if (_this.abortController) {
        _this.abortController.abort();
      }
      _this.abortController = new AbortController();
      // 创建新控制器并存储

      fetchEventSource(str, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          Authorization: this.uploadParams.headers['Authorization'],
          Accept: ['text/event-stream', 'application/json'],
        },
        body: JSON.stringify({
          task_id: id,
        }),
        openWhenHidden: true,
        signal: _this.abortController.signal, //与其相关联的signal属性
        onopen(e) {
          console.log(e, 'SSE在连接打开时被调用');
          if (e.status == 200) {
            _this.messages[_this.messages.length - 1].text = '思考中，请稍候...';
            // _this.messages[_this.messages.length - 1].text = '<h2 class="think">';
          } else {
            _this.messages[_this.messages.length - 1].text = '服务开小差了，请稍后重试';
            _this.$nextTick(() => {
              let chatBox = _this.$refs.chatBox;
              chatBox.scrollTop = chatBox.scrollHeight;
            });
          }
        },
        onmessage(msg, event) {
          console.log('收到消息:', msg, event, isMeeting, downloadUrl);

          if (msg.id) {
            _this.messages[_this.messages.length - 1].id = msg.id;
          }
          if (msg.event === 'completed') {
            const res = msg.data;
            let obj = JSON.parse(res);
            if (isMeeting) {
              axios
                .post(
                  downloadUrl,
                  {
                    task_id: id,
                  },
                  {
                    headers: {
                      Authorization: _this.uploadParams.headers['Authorization'],
                    },
                    responseType: 'blob', // 关键配置
                  },
                )
                .then((res) => {
                  // 将blob对象转换成文档
                  // 1. 创建一个Blob对象，包含文件数据,类型为docx
                  const url = window.URL.createObjectURL(new Blob([res.data]));
                  const a = document.createElement('a');
                  // 3. 设置文件名（示例为.docx，按需修改）
                  a.download = '文件.docx';
                  // 4. 创建一个链接元素
                  a.href = url;
                  a.click();
                  // 将元素添加转换成html 片段
                  _this.messages[_this.messages.length - 1].text = '<br/>已帮您自动下载该文档。';
                  // 4. 触发下载
                  // 5. 清理资源
                  window.URL.revokeObjectURL(url);
                });
            } else {
              _this.messages[_this.messages.length - 1].text = '';
              _this.messages[_this.messages.length - 1].text = obj[type];
            }
          } else if (msg.event === 'waiting') {
            _this.messages[_this.messages.length - 1].text += '.';
          } else if (msg.event === 'error') {
            // let obj = JSON.parse(res);
            const res = msg.data;
            _this.messages[_this.messages.length - 1].text = res;
          }
        },
        onclose(e) {
          _this.save_topk_paragraphs.push({ show: false, arr: _this.topk_paragraphs });
          _this.topk_paragraphs = [];
          console.log('stop', e);
          if (_this.messages[_this.messages.length - 1].id) {
            _this.messages[_this.messages.length - 1].show = true;
          }
          _this.isRequesting = false;
          _this.abortController.abort();
          _this.$forceUpdate();
        },
        onerror(err) {
          _this.messages[_this.messages.length - 1].text = '服务开小差了，请稍后重试';
          console.log(err, 'onerror');
          _this.isRequesting = false;
          _this.abortController.abort();
          _this.$forceUpdate();
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.inear-chat-btn {
  display: block;
  position: absolute;
  right: 80px;
}
.item {
  display: block !important;
}

.line {
  width: 100%;
  display: block;
  margin: 4px 0;
}

.provenance-item {
  border: 1px solid #354f8a;
  border-radius: 4px;
  font-size: 14px;
  line-height: 24px;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.icon-item {
  float: right;
}

.title-item {
  text-decoration: underline;
}

.content-item {
  color: #b3b9c4;
}
</style>
<style>
.warn-detail-bg .el-textarea__inner {
  height: auto !important;
}
.content-container table {
  width: 100%;
  border-top: 1px solid #2a548a !important;
  border-left: 1px solid #2a548a !important;
}

.content-container table td,
.content-container table th {
  border-bottom: 1px solid #2a548a !important;
  border-right: 1px solid #2a548a !important;
  font-size: 12px;
}

.content-container img {
  max-width: 100%;
}

.input-with-select .el-input-group__prepend {
  background-color: transparent;
  border: none;
  width: 4vw;
  margin-right: 4px;

  .el-input__inner {
    background-color: transparent;
    border: 2px solid #1640a4;
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;

    &:hover,
    &:active,
    &:focus {
      border: 2px solid #1640a4;
      color: #ffffff;
    }
  }
}
.input-with-select2 {
}
.input-with-select2 .el-input__inner {
  line-height: 54px;
  height: 54px;
}
.content-item h1,
h2,
h3,
h4,
h5,
h6 {
  font-size: 14px;
  padding: 0;
  margin: 0;
}
.content-item p {
  font-size: 14px;
  padding: 0;
  margin: 0;
}
.msgtext h1 {
  font-size: 14px;
  font-weight: normal;
}
.container {
  display: flex;
}
.choose-item {
  padding: 10px;
  display: block;
  background: #fff;
}
.choose-item ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.choose-item ul li {
  width: 140px;
  border: 1px solid #233999;
  text-align: center;
  margin: 0 0 10px 0;
  padding: 10px 0;
  border-radius: 4px;
  font-size: 12px;
  background-color: #fff;
  cursor: pointer;
  color: #666;
}
.choose-item ul li:hover {
  background-color: #e5f3ff;
}
.choose-item ul li.active {
  background-color: #e5f3ff;
}
.chatBox {
  padding-top: 20px;
  max-height: calc(100vh - 540px) !important;
}
.chatBox2 {
  padding-top: 20px;
  max-height: calc(100vh - 240px) !important;
  overflow: auto;
}
.select-container {
  height: 260px;
  background-color: #e5f3ff;
  color: #4d6bfe;
  border: 1px solid #4d6bfe;
  padding: 10px;
  border-radius: 4px;
  /* position: absolute;
  top: 20px;
  right: 40px; */
  width: calc(100% - 50px);
  margin-left: 10px;
  overflow: auto;
  line-height: 18px;
  margin-top: 10px;
}
.select-container2 {
  height: 164px;
}

.el-radio--small.is-bordered {
  margin-right: 2px;
}

.tag-text {
  font-size: 12px;
  background: linear-gradient(90deg, #335bff, #ca37ce);
  background-clip: border-box;
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: inline-block;
}
.meet-item {
  display: inline-block;
  width: 48%;
  background-color: #d1dcf973;
  min-height: 100px;
  vertical-align: top;
  margin-right: 1%;
  padding: 10px;
  box-sizing: border-box;
  margin-bottom: 10px;
}
.meet-item-2 {
  width: calc(97% - 0px);
  min-height: 140px;
}
.think {
  font-weight: normal;
  color: #7d93bb;
  padding-bottom: 10px;
  border-bottom: 1px solid #5893ff3b;
  margin-bottom: 10px;
}
.pos-container {
  position: relative;
}
</style>
